#include "breakvigenere.h"

#include "caesarbreak.h"

#include <QtDebug>

BreakVigenere::BreakVigenere(QByteArray alphabet, QList<qreal> langFrequencies, int keyLenght, QByteArray input, bool doXor, QObject *parent) :
    QThread(parent), alphabet(alphabet), langFrequencies(langFrequencies), keyLenght(keyLenght), input(input), doXor(doXor)
{}

void BreakVigenere::run()
{
    columns.clear();
    workers.clear();
    QList<QByteArray> caesarInputs;

    for (int col = 0; col < keyLenght; ++col)
    {
        columns << QByteArray();
        keys += '\0';
        caesarInputs << QByteArray();
    }
    for(int i = 0; i < input.size(); i++)
        caesarInputs[i % keyLenght] += input[i];
    for (int col = 0; col < keyLenght; ++col)
    {
        workers << new CaesarBreak(alphabet, langFrequencies, caesarInputs[col], doXor);
        connect(workers[col], SIGNAL(done(char,QByteArray)), this, SLOT(caesarDone(char,QByteArray)));
        workers[col]->start();
    }
    for (int col = 0; col < keyLenght; col++)
    {
//        qDebug() << "Waiting thread" <<
        workers[col]->wait();
        workers[col]->deleteLater();
    }
    QByteArray output;
    output.resize(input.size());
    for (int i = 0; i < input.size(); i++)
    {
        output[i] = columns[i % keyLenght][i / keyLenght];
//        columns[i % keyLenght].remove(0, 1);
    }
    qDebug() << "vigenere done" << keys;
    emit done(keys, output);
}

void BreakVigenere::caesarDone(char key, QByteArray plain)
{
    qDebug() << "slot called";
    CaesarBreak * caesar = qobject_cast<CaesarBreak *>(sender());
    int col = workers.indexOf(caesar);
    if (col != -1)
    {
        keys[col] = key;
        columns[col] = plain;
    }
}
